/*
 * Copyright 2011 Sina.
 *
 * Licensed under the Apache License and Weibo License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.open.weibo.com
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cmcc.aregister.ui.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.appointmentregister.sina.AccessToken;
import com.appointmentregister.sina.AsyncWeiboRunner;
import com.appointmentregister.sina.AsyncWeiboRunner.RequestListener;
import com.appointmentregister.sina.Utility;
import com.appointmentregister.sina.Weibo;
import com.appointmentregister.sina.WeiboException;
import com.appointmentregister.sina.WeiboParameters;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.oauth.data.OAuth;
import com.oauth.utils.ConfigUtil;
import com.oauth.utils.FileHelper;
import com.qqweibo.net.QAsyncHandler;
import com.qqweibo.net.QWeiboAsyncApi;
import com.qqweibo.net.QWeiboType.ResultType;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A dialog activity for sharing any text or image message to weibo. Three
 * parameters , accessToken, tokenSecret, consumer_key, are needed, otherwise a
 * WeiboException will be throwed.
 * 
 * ShareActivity should implement an interface, RequestListener which will
 * return the request result.
 * 
 * @author ZhangJie (zhangjie2@staff.sina.com.cn)
 */

public class ShareActivity_qq extends ParentActivity implements OnClickListener,
		RequestListener, QAsyncHandler {
	private final String TAG = "ShareActivity";
	private Button mSend, close;
	private TextView shareTitle;
	private RelativeLayout titleBar;
	private LinearLayout wbContentLayout;

	private String mPicPath = "";
	private String mContent = "";
	private String mAccessToken = "";
	private String mTokenSecret = "";

	public static final String EXTRA_WEIBO_CONTENT = "com.weibo.android.content";
	public static final String EXTRA_PIC_URI = "com.weibo.android.pic.uri";
	public static final String EXTRA_ACCESS_TOKEN = "com.weibo.android.accesstoken";
	public static final String EXTRA_TOKEN_SECRET = "com.weibo.android.token.secret";

	private ConfigUtil conf = ConfigUtil.getInstance();
	private OAuth oAuth = OAuth.getInstance();

	private void initAccessToken() {
		initVerifier();
		String accessToken = oAuth.getAccessToken();
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "accessToken-->" + accessToken);
		}
		String[] strs = accessToken.split("&");
		mAccessToken = strs[0].split("=")[1];
		mTokenSecret = strs[1].split("=")[1];
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "mAccessToken:" + mAccessToken + "--mTokenSecret:"
					+ mTokenSecret);
		}

	}

	private void initShareParameters() {
		Weibo.SERVER = conf.getOpenUrl();
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "openurl--->" + Weibo.SERVER);
		}
		if (conf.getCurWeibo().equals(ConfigUtil.SINAW)) {
			if (ConfigUtilHelper.debug) {
				Log.v(TAG, "conf.getCurWeibo()--->" + conf.getCurWeibo());
			}
			initSina();
		} else if (conf.getCurWeibo().equals(ConfigUtil.QQW)) {
			if (ConfigUtilHelper.debug) {
				Log.v(TAG, "conf.getCurWeibo()--->" + conf.getCurWeibo());
			}
			initQq();
		}
	}

	// 获取验证码
	private void initVerifier() {
		String url = getIntent().getStringExtra(ConfigUtil.OAUTH_VERIFIER_URL);
		Uri uri = Uri.parse(url);
		String oauth_verifier = uri.getQueryParameter("oauth_verifier");
		oAuth.setOauthVerifier(oauth_verifier);
	}

	private void initSina() {
		shareTitle.setText(getString(R.string.share_sina_title));
		titleBar.setBackgroundResource(R.drawable.sina_bg_title);
		wbContentLayout.setBackgroundResource(R.drawable.sina_bg_content);
		Weibo mWeibo = Weibo.getInstance();
		mAccessToken = conf.getSinaAccessOAuthToken();
		mTokenSecret = conf.getSinaAccessOAuthTokenSecret();
		if (mAccessToken.equals("") || mTokenSecret.equals("")) {
			initAccessToken();
			SharedPreferences tokenPreferences = getSharedPreferences(
					FileHelper.PREFERENCES_NAME, Activity.MODE_PRIVATE);
			SharedPreferences.Editor editor = tokenPreferences.edit();
			editor.putString("sinaAccessToken", mAccessToken);
			editor.putString("sinaAccessSecret", mTokenSecret);
			editor.commit();
		}
		AccessToken accessToken = new AccessToken(mAccessToken, mTokenSecret);
		mWeibo.setAccessToken(accessToken);

	}

	private void initQq() {
		shareTitle.setText(getString(R.string.share_qq_title));
		titleBar.setBackgroundResource(R.drawable.qq_bg_title);
		wbContentLayout.setBackgroundResource(R.drawable.qq_bg_content);
		mAccessToken = conf.getQqAccessOAuthToken();
		mTokenSecret = conf.getQqAccessOAuthTokenSecret();
		if (mAccessToken.equals("") || mTokenSecret.equals("")) {
			initAccessToken();
			SharedPreferences tokenPreferences = getSharedPreferences(
					FileHelper.PREFERENCES_NAME, Activity.MODE_PRIVATE);
			SharedPreferences.Editor editor = tokenPreferences.edit();
			editor.putString("qqAccessToken", mAccessToken);
			editor.putString("qqAccessSecret", mTokenSecret);
			editor.commit();
		}
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.share_mblog_view);
		shareTitle = (TextView) findViewById(R.id.share_title);
		titleBar = (RelativeLayout) findViewById(R.id.wb_title);
		wbContentLayout = (LinearLayout) findViewById(R.id.wb_content);
		close = (Button) this.findViewById(R.id.btnClose);
		close.setOnClickListener(this);
		mSend = (Button) this.findViewById(R.id.btnSend);
		mSend.setOnClickListener(this);
		initShareParameters();
	}

	private String log;

	private void sending() {
		showProgressDlg(getString(R.string.dialog_sending));
	}

	public void progressRun() {
		senStatus();
	}

	public void doWork() {
		showTostDlg(log);
		conf.setSinaAccessOAuthToken("");
		conf.setSinaAccessOAuthTokenSecret("");
		conf.setQqAccessOAuthToken("");
		conf.setQqAccessOAuthTokenSecret("");
		finish();
	}

	public void singleBtnWork() {
		// finish();
	}

	private void senStatus() {
		if (conf.getCurWeibo().equals(ConfigUtil.SINAW)) {
			sinaSend();
		} else if (conf.getCurWeibo().equals(ConfigUtil.QQW)) {
			qqSend();
		}
	}

	private void sinaSend() {
		mContent = getString(R.string.weibo_default_words) + getPhotoFileName();
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "content-->" + this.mContent);
		}
		Weibo weibo = Weibo.getInstance();
		try {
			if (!TextUtils
					.isEmpty((String) (weibo.getAccessToken().getToken()))) {
				if (!TextUtils.isEmpty(mPicPath)) {
					upload(weibo, conf.getAppKey(), this.mPicPath,
							this.mContent, "", "");
				} else {

					update(weibo, conf.getAppKey(), mContent, "", "");
					if (ConfigUtilHelper.debug) {
						Log.i(TAG, "----update-----end----");
					}
				}
			} else {
				Toast.makeText(this, this.getString(R.string.please_login),
						Toast.LENGTH_LONG);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			if (ConfigUtilHelper.debug) {
				Log.i(TAG, e.getMessage());
			}
		} catch (IOException e) {
			e.printStackTrace();
			if (ConfigUtilHelper.debug) {
				Log.i(TAG, e.getMessage());
			}
		} catch (WeiboException e) {
			e.printStackTrace();
			if (ConfigUtilHelper.debug) {
				Log.i(TAG, e.getMessage());
			}
		}
	}

	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
		String randomTime = dateFormat.format(date);
		return " " + randomTime;
	}

	private void qqSend() {
		mContent = getString(R.string.weibo_default_words) + getPhotoFileName();
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "content-->" + this.mContent);
		}
		QWeiboAsyncApi api = new QWeiboAsyncApi();
		api.publishMsg(conf.getAppKey(), conf.getAppSecret(), mAccessToken,
				mTokenSecret, this.mContent, this.mPicPath,
				ResultType.ResultType_Json, this);
	}

	@Override
	public void onClick(View v) {
		int viewId = v.getId();
		switch (viewId) {
		case R.id.btnClose: {
			finish();
			break;
		}
		case R.id.btnSend: {
			sending();
			break;
		}
		default:
		}
	}

	private String upload(Weibo weibo, String appKey, String file,
			String content, String lon, String lat) throws WeiboException {
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", appKey);
		bundle.add("pic", file);
		bundle.add("status", content);
		if (!TextUtils.isEmpty(lon)) {
			bundle.add("lon", lon);
		}
		if (!TextUtils.isEmpty(lat)) {
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/upload.json";
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);

		return rlt;
	}

	private String update(Weibo weibo, String file, String content, String lon,
			String lat) throws MalformedURLException, IOException,
			WeiboException {
		if (ConfigUtilHelper.debug) {
			Log.i(TAG, "----111111----");
		}
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", file);
		bundle.add("status", content);
		if (!TextUtils.isEmpty(lon)) {
			bundle.add("lon", lon);
		}
		if (!TextUtils.isEmpty(lat)) {
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/update.json";
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);
		if (ConfigUtilHelper.debug) {
			Log.i(TAG, "----222222----");
		}
		return rlt;
	}

	@Override
	public void onComplete(String response) {
		log = getString(R.string.share_activity_share_success);
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "--onComplete response-->" + response);
		}
		Toast.makeText(this, R.string.share_activity_share_success,
				Toast.LENGTH_LONG);
		this.finish();
	}

	@Override
	public void onIOException(IOException e) {
		// TODO Auto-generated method stub
		log = getString(R.string.share_activity_share_failed_network);
	}

	@Override
	public void onError(WeiboException e) {
		log = getString(R.string.share_activity_share_failed);
		if (e.getStatusCode() == -1) {
			log = getString(R.string.share_activity_share_failed_network);
		}
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, getString(R.string.share_activity_share_failed)
					+ "---------e.getMessage()---------->" + e.getMessage()
					+ "statuscode-->" + e.getStatusCode());
		}
	}

	@Override
	public void onThrowable(Throwable t, Object cookie) {
		// TODO Auto-generated method stub
		log = getString(R.string.share_activity_share_failed_network);
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "error");
		}
	}

	@Override
	public void onCompleted(int statusCode, String content, Object cookie) {
		// TODO Auto-generated method stub
		log = getString(R.string.share_activity_share_success);
		if (ConfigUtilHelper.debug) {
			Log.v(TAG, "success");
		}
	}

	public void showTostDlg(String msg) {
		Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.BOTTOM, 0, 50);
		toast.show();
	}

	public void showProgressDlg(String msg) {
		final ProgressDialog loadingDlg = new ProgressDialog(this);
		loadingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		loadingDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
		loadingDlg.setMessage(msg);
		loadingDlg.setCancelable(false);
		loadingDlg.show();
		new Thread() {
			public void run() {
				try {
					progressRun();
				} catch (Exception e) {
					loadingDlg.dismiss();
				}
				loadingDlg.dismiss();
			}
		}.start();
		loadingDlg
				.setOnDismissListener(new DialogInterface.OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						// TODO Auto-generated method stub
						doWork();
					}

				});
	}
}
